package com.practice.mybpapi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.practice.mybpapi.domain.dto.*;
import com.practice.mybpapi.domain.po.Address;
import com.practice.mybpapi.domain.po.User;
import com.practice.mybpapi.enums.UserStatus;
import com.practice.mybpapi.mapper.UserMapper;
import com.practice.mybpapi.service.UserService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public void decrease(Long id, Integer money) {
        //获取用户信息
        User user = this.getById(id);
        if(user==null||user.getStatus() == UserStatus.FREEZE){
            throw new RuntimeException("用户不存在或已冻结");
        }
        if(user.getBalance() < money){
            throw new RuntimeException("余额不足");
        }
        //baseMapper.deductBalance(id, money);
        var balance = user.getBalance() - money;
        /*LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        this.update(updateWrapper);*/
        lambdaUpdate().eq(User::getId, id)
                .eq(User::getStatus, 1)
                .eq(User::getBalance, user.getBalance())
                .set(User::getBalance, balance)
                .set(balance ==0, User::getStatus, 2)
                .update();

    }

    @Override
    public List<QueryUserVo> queryUser(UserQuery query) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(query.getName() != null, User::getUsername, query.getName())
                .eq(query.getStatus() != null, User::getStatus, query.getStatus())
                .ge(query.getMinBalance() != null, User::getBalance, query.getMinBalance())
                .le(query.getMaxBalance() != null, User::getBalance, query.getMaxBalance());
                List<User> users = baseMapper.selectList(queryWrapper);
                return BeanUtil.copyToList(users, QueryUserVo.class);
    }

    @Override
    public QueryUserVo getUserAddress(Long id) {
        User user = this.getById(id);
        List<Address> list = Db.lambdaQuery(Address.class)
                .eq(Address::getUserId, id)
                .select(Address::getProvince, Address::getCity, Address::getTown, Address::getMobile)
                .list();
        QueryUserVo queryUserVo = BeanUtil.copyProperties(user, QueryUserVo.class);
        queryUserVo.setAddresses(BeanUtil.copyToList(list, AddressVO.class));
        return queryUserVo;
    }

    @Override
    public List<QueryUserVo> batchGetUserAddress(List<Long> ids) {
        //参照getUserAddress方法完成批量查询
        List<User> users = this.listByIds(ids);
        if (users.isEmpty()){
            return Collections.emptyList();
        }
        List<QueryUserVo> queryUserVos = BeanUtil.copyToList(users, QueryUserVo.class);
        //一次性查出所有地址
        List<Address> list = Db.lambdaQuery(Address.class)
                .in(Address::getUserId, ids)
                .select(Address::getProvince, Address::getCity, Address::getTown, Address::getMobile, Address::getUserId)
                .list();
        List<AddressVO> addressVOS = BeanUtil.copyToList(list, AddressVO.class);
        queryUserVos.forEach(queryUserVo -> {
            queryUserVo.setAddresses(addressVOS.stream()
                    .filter(addressVO -> addressVO.getUserId().equals(queryUserVo.getId()))
                    .toList());
        });
        return queryUserVos;
    }

    @Override
    public PageBase<QueryUserVo> pagedQueryUser(PageUserQuery query) {

        //分页查询
        Page<User> page = query.toMapPageSortByUpdateTime();

        //name模糊查询 status精确查询
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        wrapper.like(query.getName() != null, "username", query.getName())
                .eq(query.getStatus() != null, "status", query.getStatus());
        var pageRel = this.page(page, wrapper);
        /* pageRel = lambdaQuery().like(query.getName() != null, User::getUsername, query.getName())
                .eq(query.getStatus() != null, User::getStatus, query.getStatus())
                .page(page)*/
        //封装分页结果
        return PageBase.of(pageRel);
    }
}